#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/16 14:11
# @Author  : Zangzihan
# @File    : polygon2rectangle.py
# @Description : 这个把多边形的多个顶点计算最小外接矩形，并保存矩形的四个点顶点
import cv2
import numpy as np
import os
import json
import copy
def process_label_only(path_dir):
    try:
        for filename in os.listdir(path_dir):
            if filename.endswith('.json'):

                with open(os.path.join(path_dir, filename), "r") as f:
                    content = f.read()
                threshInfo = json.loads(content)

                threshInfo_revise = copy.deepcopy(threshInfo)

                for id, data in enumerate(threshInfo["shapes"]):
                    black_img = np.zeros((threshInfo["imageHeight"], threshInfo["imageWidth"]), dtype=np.uint8)
                    coor = data["points"]
                    # pts = np.array([[coor[0][0], coor[0][1]], [coor[1][0], coor[1][1]], [coor[2][0], coor[2][1]], [coor[3][0], coor[3][1]]], dtype=np.int32)
                    pts = np.array(coor, dtype=np.int32)
                    cv2.fillPoly(black_img, [pts], (255))

                    # cv2.namedWindow("temp", cv2.WINDOW_NORMAL)
                    # cv2.imshow("temp", black_img)
                    # cv2.waitKey()

                    # 连通域分析
                    _, labels, stats, centroids = cv2.connectedComponentsWithStats(black_img)

                    # 计算旋转角度和中心点
                    largest_label = np.argmax(stats[1:, cv2.CC_STAT_AREA]) + 1
                    center_x, center_y = centroids[largest_label]
                    width, height = stats[largest_label, cv2.CC_STAT_WIDTH], stats[largest_label, cv2.CC_STAT_HEIGHT]
                    rect = cv2.minAreaRect(np.argwhere(labels == largest_label))
                    box = cv2.boxPoints(rect)
                    box = np.int32(box)
                    angle = 90 - rect[-1]

                    print("旋转角度:", angle)
                    print("中心点坐标:", int(center_x), int(center_y))

                    # 按照左上，右上，右下，左下的顺序输出角点坐标
                    print("左上角点坐标：", box[1][1], box[1][0])
                    print("右上角点坐标：", box[0][1], box[0][0])
                    print("右下角点坐标：", box[3][1], box[3][0])
                    print("左下角点坐标：", box[2][1], box[2][0])

                    black_img2 = np.zeros((threshInfo["imageHeight"], threshInfo["imageWidth"]), dtype=np.uint8)
                    pts = np.array([[box[1][1], box[1][0]], [box[0][1], box[0][0]], [box[3][1], box[3][0]], [box[2][1], box[2][0]]], dtype=np.int32)
                    cv2.fillPoly(black_img2, [pts], (255))

                    # cv2.namedWindow("temp2", cv2.WINDOW_NORMAL)
                    # cv2.imshow("temp2", black_img2)
                    # cv2.waitKey()

                    threshInfo_revise["shapes"][id]["points"] = [[int(box[1][1]), int(box[1][0])], [int(box[0][1]), int(box[0][0])], [int(box[3][1]), int(box[3][0])], [int(box[2][1]), int(box[2][0])]]
                    b = 1
                with open(os.path.join(path_dir, filename), "w") as f:
                    json.dump(threshInfo_revise, f, indent=4)
                b = 1
        return True
    except BaseException as e:
        print("标签格式转换失败： {}".format(e.args))
        return False

if __name__ == '__main__':
    process_label_only(r"F:\0shougang\ir\Images_d_d_d")